[[...path]].page.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. import React, { ReactNode, useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import type {
  11. GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { useCurrentGrowiLayoutFluidClassName, useEditorModeClassName } from '~/client/services/layout';
  19. import { PageView } from '~/components/Page/PageView';
  20. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  21. import type { CrowiRequest } from '~/interfaces/crowi-request';
  22. import type { EditorConfig } from '~/interfaces/editor-settings';
  23. import type { IPageGrantData } from '~/interfaces/page';
  24. import type { RendererConfig } from '~/interfaces/services/renderer';
  25. import type { PageModel, PageDocument } from '~/server/models/page';
  26. import type { PageRedirectModel } from '~/server/models/page-redirect';
  27. import {
  28. useCurrentUser,
  29. useIsLatestRevision,
  30. useIsForbidden, useIsNotFound, useIsSharedUser,
  31. useIsEnabledStaleNotification, useIsIdenticalPath,
  32. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  33. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  34. useIsAclEnabled, useIsSearchPage, useTemplateTagData, useTemplateBodyData, useIsEnabledAttachTitleHeader,
  35. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPathname,
  36. useIsSlackConfigured, useRendererConfig,
  37. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  38. } from '~/stores/context';
  39. import { useEditingMarkdown } from '~/stores/editor';
  40. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  41. import { useSWRxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId } from '~/stores/page';
  42. import { useRedirectFrom } from '~/stores/page-redirect';
  43. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  44. import { useSelectedGrant } from '~/stores/ui';
  45. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  46. import loggerFactory from '~/utils/logger';
  47. import { BasicLayout } from '../components/Layout/BasicLayout';
  48. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  49. import type { GrowiSubNavigationSwitcherProps } from '../components/Navbar/GrowiSubNavigationSwitcher';
  50. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  51. import type { NextPageWithLayout } from './_app.page';
  52. import type { CommonProps } from './utils/commons';
  53. import {
  54. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig,
  55. } from './utils/commons';
  56. declare global {
  57. // eslint-disable-next-line vars-on-top, no-var
  58. var globalEmitter: EventEmitter;
  59. }
  60. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  61. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  62. const GrowiSubNavigationSwitcher = dynamic<GrowiSubNavigationSwitcherProps>(() => import('../components/Navbar/GrowiSubNavigationSwitcher')
  63. .then(mod => mod.GrowiSubNavigationSwitcher), { ssr: false });
  64. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  65. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  66. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  67. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  68. const logger = loggerFactory('growi:pages:all');
  69. const {
  70. isPermalink: _isPermalink, isTrashPage: _isTrashPage, isCreatablePage,
  71. } = pagePathUtils;
  72. const { removeHeadingSlash } = pathUtils;
  73. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  74. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  75. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  76. {
  77. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  78. return v?.data != null
  79. && v?.data.toObject != null
  80. && v?.meta != null
  81. && isIPageInfoForEntity(v.meta);
  82. },
  83. serialize: (v) => {
  84. return {
  85. data: superjson.stringify(v.data.toObject()),
  86. meta: superjson.stringify(v.meta),
  87. };
  88. },
  89. deserialize: (v) => {
  90. return {
  91. data: superjson.parse(v.data),
  92. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  93. };
  94. },
  95. },
  96. 'IPageToShowRevisionWithMetaTransformer',
  97. );
  98. // GrowiContextualSubNavigation for NOT shared page
  99. type GrowiContextualSubNavigationProps = {
  100. isLinkSharingDisabled: boolean,
  101. }
  102. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  103. const { isLinkSharingDisabled } = props;
  104. const { data: currentPage } = useSWRxCurrentPage();
  105. return (
  106. <div data-testid="grw-contextual-sub-nav">
  107. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  108. </div>
  109. );
  110. };
  111. const PutbackPageModal = (): JSX.Element => {
  112. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  113. return <PutbackPageModal />;
  114. };
  115. type Props = CommonProps & {
  116. pageWithMeta: IPageToShowRevisionWithMeta | null,
  117. // pageUser?: any,
  118. redirectFrom?: string;
  119. // shareLinkId?: string;
  120. isLatestRevision?: boolean,
  121. isIdenticalPathPage?: boolean,
  122. isForbidden: boolean,
  123. isNotFound: boolean,
  124. isNotCreatable: boolean,
  125. // isAbleToDeleteCompletely: boolean,
  126. templateTagData?: string[],
  127. templateBodyData?: string,
  128. isSearchServiceConfigured: boolean,
  129. isSearchServiceReachable: boolean,
  130. isSearchScopeChildrenAsDefault: boolean,
  131. isSlackConfigured: boolean,
  132. // isMailerSetup: boolean,
  133. isAclEnabled: boolean,
  134. // hasSlackConfig: boolean,
  135. drawioUri: string | null,
  136. hackmdUri: string,
  137. noCdn: string,
  138. // highlightJsStyle: string,
  139. isAllReplyShown: boolean,
  140. isContainerFluid: boolean,
  141. editorConfig: EditorConfig,
  142. isEnabledStaleNotification: boolean,
  143. isEnabledAttachTitleHeader: boolean,
  144. // isEnabledLinebreaks: boolean,
  145. // isEnabledLinebreaksInComments: boolean,
  146. adminPreferredIndentSize: number,
  147. isIndentSizeForced: boolean,
  148. disableLinkSharing: boolean,
  149. grantData?: IPageGrantData,
  150. rendererConfig: RendererConfig,
  151. };
  152. const Page: NextPageWithLayout<Props> = (props: Props) => {
  153. // register global EventEmitter
  154. if (isClient() && window.globalEmitter == null) {
  155. window.globalEmitter = new EventEmitter();
  156. }
  157. const router = useRouter();
  158. useCurrentUser(props.currentUser ?? null);
  159. // commons
  160. useEditorConfig(props.editorConfig);
  161. useCsrfToken(props.csrfToken);
  162. // page
  163. useIsLatestRevision(props.isLatestRevision);
  164. useIsContainerFluid(props.isContainerFluid);
  165. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  166. useIsForbidden(props.isForbidden);
  167. useIsNotFound(props.isNotFound);
  168. useIsNotCreatable(props.isNotCreatable);
  169. useRedirectFrom(props.redirectFrom ?? null);
  170. useIsSharedUser(false); // this page cann't be routed for '/share'
  171. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  172. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  173. useIsSearchPage(false);
  174. useTemplateTagData(props.templateTagData);
  175. useTemplateBodyData(props.templateBodyData);
  176. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  177. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  178. useIsSearchServiceReachable(props.isSearchServiceReachable);
  179. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  180. useIsSlackConfigured(props.isSlackConfigured);
  181. // useIsMailerSetup(props.isMailerSetup);
  182. useIsAclEnabled(props.isAclEnabled);
  183. // useHasSlackConfig(props.hasSlackConfig);
  184. useDrawioUri(props.drawioUri);
  185. useHackmdUri(props.hackmdUri);
  186. // useNoCdn(props.noCdn);
  187. useDefaultIndentSize(props.adminPreferredIndentSize);
  188. useIsIndentSizeForced(props.isIndentSizeForced);
  189. useDisableLinkSharing(props.disableLinkSharing);
  190. useRendererConfig(props.rendererConfig);
  191. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  192. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  193. useIsAllReplyShown(props.isAllReplyShown);
  194. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  195. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  196. const { pageWithMeta } = props;
  197. const pageId = pageWithMeta?.data._id;
  198. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  199. const revisionBody = pageWithMeta?.data.revision?.body;
  200. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  201. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  202. useCurrentPathname(props.currentPathname);
  203. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  204. const { mutate: mutateCurrentPageId } = useCurrentPageId();
  205. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  206. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  207. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  208. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  209. const { mutate: mutateRevisionIdHackmdSynced } = useRevisionIdHackmdSynced();
  210. useSetupGlobalSocket();
  211. useSetupGlobalSocketForPage(pageId);
  212. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName(pageWithMeta?.data);
  213. const shouldRenderPutbackPageModal = pageWithMeta != null
  214. ? _isTrashPage(pageWithMeta.data.path)
  215. : false;
  216. // sync grant data
  217. useEffect(() => {
  218. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  219. mutateSelectedGrant(grantDataToApply);
  220. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  221. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  222. useEffect(() => {
  223. const decodedURI = decodeURI(window.location.pathname);
  224. if (isClient() && decodedURI !== props.currentPathname) {
  225. const { search, hash } = window.location;
  226. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  227. }
  228. }, [props.currentPathname, router]);
  229. // initialize mutateEditingMarkdown only once per page
  230. // need to include useCurrentPathname not useCurrentPagePath
  231. useEffect(() => {
  232. if (props.currentPathname != null) {
  233. mutateEditingMarkdown(revisionBody);
  234. }
  235. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  236. useEffect(() => {
  237. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  238. mutateRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  239. }, [mutateRemoteRevisionId, mutateRevisionIdHackmdSynced, pageWithMeta?.data.revision?._id, pageWithMeta?.data.revisionHackmdSynced]);
  240. useEffect(() => {
  241. mutateCurrentPageId(pageId ?? null);
  242. }, [mutateCurrentPageId, pageId]);
  243. const title = generateCustomTitleForPage(props, pagePath);
  244. return (
  245. <>
  246. <Head>
  247. <title>{title}</title>
  248. </Head>
  249. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  250. <header className="py-0 position-relative">
  251. <div id="grw-subnav-container">
  252. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  253. </div>
  254. </header>
  255. <div className="d-edit-none">
  256. <GrowiSubNavigationSwitcher isLinkSharingDisabled={props.disableLinkSharing} />
  257. </div>
  258. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  259. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  260. <DisplaySwitcher
  261. pageView={
  262. <PageView
  263. pagePath={pagePath}
  264. initialPage={pageWithMeta?.data}
  265. rendererConfig={props.rendererConfig}
  266. />
  267. }
  268. />
  269. <PageStatusAlert />
  270. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  271. </div>
  272. </>
  273. );
  274. };
  275. type LayoutProps = Props & {
  276. children?: ReactNode
  277. }
  278. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  279. const className = useEditorModeClassName();
  280. // init sidebar config with UserUISettings and sidebarConfig
  281. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  282. return (
  283. <BasicLayout className={className}>
  284. {children}
  285. </BasicLayout>
  286. );
  287. };
  288. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  289. return (
  290. <>
  291. <DrawioViewerScript />
  292. <Layout {...page.props}>
  293. {page}
  294. </Layout>
  295. <UnsavedAlertDialog />
  296. <DescendantsPageListModal />
  297. <DrawioModal />
  298. <HandsontableModal />
  299. <TemplateModal />
  300. </>
  301. );
  302. };
  303. function getPageIdFromPathname(currentPathname: string): string | null {
  304. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  305. }
  306. class MultiplePagesHitsError extends ExtensibleCustomError {
  307. pagePath: string;
  308. constructor(pagePath: string) {
  309. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  310. this.pagePath = pagePath;
  311. }
  312. }
  313. // apply parent page grant fot creating page
  314. async function applyGrantToPage(props: Props, ancestor: any) {
  315. await ancestor.populate('grantedGroup');
  316. const grant = {
  317. grant: ancestor.grant,
  318. };
  319. const grantedGroup = ancestor.grantedGroup ? {
  320. grantedGroup: {
  321. id: ancestor.grantedGroup.id,
  322. name: ancestor.grantedGroup.name,
  323. },
  324. } : {};
  325. props.grantData = Object.assign(grant, grantedGroup);
  326. }
  327. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  328. const { model: mongooseModel } = await import('mongoose');
  329. const req: CrowiRequest = context.req as CrowiRequest;
  330. const { crowi } = req;
  331. const { revisionId } = req.query;
  332. const Page = crowi.model('Page') as PageModel;
  333. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  334. const { pageService } = crowi;
  335. let currentPathname = props.currentPathname;
  336. const pageId = getPageIdFromPathname(currentPathname);
  337. const isPermalink = _isPermalink(currentPathname);
  338. const { user } = req;
  339. if (!isPermalink) {
  340. // check redirects
  341. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  342. if (chains != null) {
  343. // overwrite currentPathname
  344. currentPathname = chains.end.toPath;
  345. props.currentPathname = currentPathname;
  346. // set redirectFrom
  347. props.redirectFrom = chains.start.fromPath;
  348. }
  349. // check whether the specified page path hits to multiple pages
  350. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  351. if (count > 1) {
  352. throw new MultiplePagesHitsError(currentPathname);
  353. }
  354. }
  355. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  356. const page = pageWithMeta?.data as unknown as PageDocument;
  357. // add user to seen users
  358. if (page != null && user != null) {
  359. await page.seen(user);
  360. }
  361. // populate & check if the revision is latest
  362. if (page != null) {
  363. page.initLatestRevisionField(revisionId);
  364. await page.populateDataToShowRevision();
  365. props.isLatestRevision = page.isLatestRevision();
  366. }
  367. if (page == null && user != null) {
  368. const templateData = await Page.findTemplate(props.currentPathname);
  369. if (templateData != null) {
  370. props.templateTagData = templateData.templateTags as string[];
  371. props.templateBodyData = templateData.templateBody as string;
  372. }
  373. // apply pagrent page grant
  374. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  375. if (ancestor != null) {
  376. await applyGrantToPage(props, ancestor);
  377. }
  378. }
  379. props.pageWithMeta = pageWithMeta;
  380. }
  381. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  382. const req: CrowiRequest = context.req as CrowiRequest;
  383. const { crowi } = req;
  384. const Page = crowi.model('Page') as PageModel;
  385. const { currentPathname } = props;
  386. const pageId = getPageIdFromPathname(currentPathname);
  387. const isPermalink = _isPermalink(currentPathname);
  388. const page = props.pageWithMeta?.data;
  389. if (props.isIdenticalPathPage) {
  390. props.isNotCreatable = true;
  391. }
  392. else if (page == null) {
  393. props.isNotFound = true;
  394. props.isNotCreatable = !isCreatablePage(currentPathname);
  395. // check the page is forbidden or just does not exist.
  396. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  397. props.isForbidden = count > 0;
  398. }
  399. else {
  400. props.isNotFound = page.isEmpty;
  401. props.isNotCreatable = false;
  402. props.isForbidden = false;
  403. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  404. if (isPermalink && page.isEmpty) {
  405. props.currentPathname = page.path;
  406. }
  407. // /path/to/page ==> /62a88db47fed8b2d94f30000
  408. if (!isPermalink && !page.isEmpty) {
  409. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  410. if (!isToppage) {
  411. props.currentPathname = `/${page._id}`;
  412. }
  413. }
  414. }
  415. }
  416. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  417. // const req: CrowiRequest = context.req as CrowiRequest;
  418. // const { crowi } = req;
  419. // const UserModel = crowi.model('User');
  420. // if (isUserPage(props.currentPagePath)) {
  421. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  422. // if (user != null) {
  423. // props.pageUser = JSON.stringify(user.toObject());
  424. // }
  425. // }
  426. // }
  427. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  428. const req: CrowiRequest = context.req as CrowiRequest;
  429. const { crowi } = req;
  430. const {
  431. searchService, configManager, aclService,
  432. } = crowi;
  433. props.isSearchServiceConfigured = searchService.isConfigured;
  434. props.isSearchServiceReachable = searchService.isReachable;
  435. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  436. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  437. // props.isMailerSetup = mailService.isMailerSetup;
  438. props.isAclEnabled = aclService.isAclEnabled();
  439. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  440. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  441. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  442. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  443. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  444. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  445. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  446. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  447. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  448. props.editorConfig = {
  449. upload: {
  450. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  451. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  452. },
  453. };
  454. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  455. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  456. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  457. props.rendererConfig = {
  458. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  459. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  460. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  461. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  462. plantumlUri: process.env.PLANTUML_URI ?? null,
  463. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  464. // XSS Options
  465. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  466. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  467. attrWhiteList: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  468. tagWhiteList: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  469. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  470. };
  471. }
  472. /**
  473. * for Server Side Translations
  474. * @param context
  475. * @param props
  476. * @param namespacesRequired
  477. */
  478. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  479. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  480. props._nextI18Next = nextI18NextConfig._nextI18Next;
  481. }
  482. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  483. const req = context.req as CrowiRequest<IUserHasId & any>;
  484. const { user } = req;
  485. const result = await getServerSideCommonProps(context);
  486. // check for presence
  487. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  488. if (!('props' in result)) {
  489. throw new Error('invalid getSSP result');
  490. }
  491. const props: Props = result.props as Props;
  492. if (props.redirectDestination != null) {
  493. return {
  494. redirect: {
  495. permanent: false,
  496. destination: props.redirectDestination,
  497. },
  498. };
  499. }
  500. if (user != null) {
  501. props.currentUser = user.toObject();
  502. }
  503. try {
  504. await injectPageData(context, props);
  505. }
  506. catch (err) {
  507. if (err instanceof MultiplePagesHitsError) {
  508. props.isIdenticalPathPage = true;
  509. }
  510. else {
  511. throw err;
  512. }
  513. }
  514. await injectRoutingInformation(context, props);
  515. injectServerConfigurations(context, props);
  516. await injectNextI18NextConfigurations(context, props, ['translation']);
  517. return {
  518. props,
  519. };
  520. };
  521. export default Page;